package tq.com.tqstudent.ui.activity.classes;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.cropimage.tq.ImagePicker;
import com.cropimage.tq.cropper.CropImage;
import com.google.gson.Gson;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.FileUtil;
import com.lib.common.utils.ImgUtils;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.NotchUtils;
import com.lib.common.utils.PermissionConstant;
import com.lib.common.utils.SPUtils;
import com.lib.common.utils.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import tq.com.tqandroidim.ITQIMObserver;
import tq.com.tqandroidim.TQIM;
import tq.com.tqandroidim.TQIMMsg;
import tq.com.tqandroidim.TQIMStatus;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.adapter.ChatAdapter;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.ChatBean;
import tq.com.tqstudent.bean.ChatReceiveBean;
import tq.com.tqstudent.bean.ChatRecodeBean;
import tq.com.tqstudent.bean.SimpleBaseBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.event.ChatEvent;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.SimpleDialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.utils.MatisseImageEngine;
import tq.com.tqstudent.utils.VarietyUtil;
import tq.com.tqstudent.views.InputConflictView;
import tq.com.tqstudent.widgets.TopSmoothScroller;

/**
 * @Author rames
 * @date 2019/3/14 10:30
 */
public class ChatActivity extends BaseActivity  {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.keyboard_layout)
    InputConflictView conflictView;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.test_iv)
    ImageView testIV;

    private int commentID;
    private int groupID;
    private int pageNO = 1;
    private int index = 0;
    private boolean isGroup = false;
    private boolean isCanLoading = true; // 是否还有历史数据
    private String nickName;
    private ChatAdapter adapter;
    private ImagePicker imagePicker;
    private final int REQUEST_CODE_CHOOSE = 0x131;

    public static void show(Activity activity, boolean isGroup, String nickName, int commentID, int groupId){
        show(activity, isGroup, nickName, commentID, groupId, 0);
    }

    /**
     * @param activity
     * @param nickName
     * @param commentID 私信id
     * @param groupId 群的id
     * @param index 上一页的item处于列表的第几项,主要用于更新最后一条数据
     */
    public static void show(Activity activity, boolean isGroup, String nickName, int commentID, int groupId, int index){
        Intent intent = new Intent(activity, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("nickName", nickName);
        bundle.putInt("commentID", commentID);
        bundle.putInt("groupId", groupId);
        bundle.putBoolean("isGroup", isGroup);
        bundle.putInt("index", index);

        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void getExtras(Bundle extras) {
        nickName = extras.getString("nickName");
        commentID = extras.getInt("commentID");
        isGroup = extras.getBoolean("isGroup");
        groupID = extras.getInt("groupId");
        index = extras.getInt("index");
    }

    @Override
    public int initLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected boolean setAdaptNotchBar() {
        return false;
    }

    @Override
    protected boolean setStatusBarTranslate() {
        return false; // 不能设置true,不然输入框弹不起来
    }

    @Override
    protected void setLayoutViewBefore() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.color_title_bg), 0);
    }

    @Override
    protected void onDestroy() {
        TQIM.getShareIm().removeObserver(mITQIMObserver);
        App.stopImWhenLogout();
        int recvId = commentID;
        if(isGroup){
            recvId = groupID;
        }
        setReadPoint(recvId, isGroup);

//        if(adapter != null) {
//            List<ChatBean> list = adapter.getDatas();
//            if (list.size() > 0) {
//                ChatBean bean = list.get(list.size() - 1);
//                ChatEvent event = new ChatEvent(bean, index);
//                EventBus.getDefault().post(event);
//            }
//        }
        EventBus.getDefault().post(new ChatEvent());
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SPUtils.getInstance(this).putBoolean(Constants.IS_CHAT_ACTIVITY_PUSH, true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        SPUtils.getInstance(this).putBoolean(Constants.IS_CHAT_ACTIVITY_PUSH, false);
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle(nickName);
        App.startImWhenLogin();

        if(!isGroup){
            Glide.with(this).load(VarietyUtil.getHeadImgUri(UserInfo.getHeadImg())).into(conflictView.getGroupIV());
        }

        notch();
        initImagePicker();

        //控制布局为LinearLayout或者是GridView或者是瀑布流布局
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//        layoutManager.setStackFromEnd(true);
        recyclerView.setFocusableInTouchMode(false);
        recyclerView.setFocusable(false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ChatAdapter(new ArrayList<>(), this);
        recyclerView.setAdapter(adapter);
        // 设置item及item中控件的点击事件
        adapter.setOnItemClickListener(ChatItemClickListener);

        conflictView.setOnViewClickListener(new InputConflictView.OnViewClickListener() {
            @Override
            public void onClick(int index) {
                switch (index){
                    // 发送
                    case 1:
                        if(contentEdit.getText().toString().trim().length() < 1){
                            showToast("不能发空白消息");
                            return;
                        }

                        String content = contentEdit.getText().toString().trim();
                        sendMessage(content, 0, true);
                        break;

                        // 拍照
                    case 2:
                        getPermission(true);
                        break;

                        // 群组
                    case 3:
//                        showToast("群组");
                        break;

                        // 输入法弹出来了
                    case 4:
                        recyclerView.scrollToPosition((null == adapter || adapter.getItemCount() == 0) ? 0 : adapter.getItemCount() - 1);
                        break;
                }
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                //newState分 0,1,2三个状态,2是滚动状态,0是停止
                super.onScrollStateChanged(recyclerView, newState);
                //-1代表顶部,返回true表示没到顶,还可以滑
                //1代表底部,返回true表示没到底部,还可以滑
                if(newState != 0) return;
                if(!recyclerView.canScrollVertically(-1)){
                    if(isCanLoading){
                        pageNO++;
                        getRecodeTask();
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        TQIM.getShareIm().addObserver(mITQIMObserver);
    }

    private void getPermission(boolean isCamera){
        AndPermission.with(this)
                .runtime()
                .permission(PermissionConstant.PERMISSIONS_OF_IMAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        headPicker(isCamera);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        showToast("用户已禁止访问图片权限");
                    }
                })
                .start();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void notch(){
        // 如果有刘海
        if (NotchUtils.hasNotchScreen(this) && null != getTitleView()) {
            int notchHeight = NotchUtils.getNotchHeight(this);
            LogUtil.e("notchHeight: "+notchHeight);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) getTitleView().getLayoutParams();
            params.setMargins(0, 0, 0, 0);
            getTitleView().setLayoutParams(params);
        }
    }

    @Override
    public void initData() {
        getRecodeTask();
    }

    private void buildDatas(List<ChatRecodeBean> list){
        List<ChatBean> chatList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ChatRecodeBean bean = list.get(i);

            if(getBeanType(bean.sender.id, bean.content_type) == ChatBean.TYPE_OPPOSITE_VIDEO){
                ChatBean chat = new ChatBean();
                chat.type = ChatBean.TYPE_OPPOSITE_VIDEO;
                chat.icon = bean.sender.pic;
                chat.username = bean.sender.name;
                chat.title = "";
                chat.contentType = bean.content_type;
                chat.videoUrl = bean.content;
                chatList.add(chat);
            } else {
                chatList.add(new ChatBean(getBeanType(bean.sender.id, bean.content_type), bean.content_type, bean.sender.pic, bean.sender.name, bean.content, bean.content));
            }
        }

        List<ChatBean> datas = new ArrayList<>();
        datas.addAll(chatList);
        datas.addAll(adapter.getDatas());
        adapter.setDatas(datas);

        if(pageNO == 1) {
            recyclerView.scrollToPosition((null == adapter || adapter.getItemCount() == 0) ? 0 : adapter.getItemCount() - 1);
        } else {
            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            LinearSmoothScroller s2 = new TopSmoothScroller(this);
            s2.setTargetPosition(20);
            layoutManager.startSmoothScroll(s2);
            recyclerView.smoothScrollToPosition(0);
        }
    }

    private int getBeanType(int userID, int type){
        if(userID != UserInfo.getUserID()){
            if(type == ChatBean.CONTENT_TYPE_TEXT){
                return ChatBean.TYPE_OPPOSITE_TEXT;
            } else if(type == ChatBean.CONTENT_TYPE_IMAGE) {
                return ChatBean.TYPE_OPPOSITE_IMAGE;
            } else {
                return ChatBean.TYPE_OPPOSITE_VIDEO;
            }
        } else {
            if(type == ChatBean.CONTENT_TYPE_TEXT){
                return ChatBean.TYPE_MINE_TEXT;
            } else {
                return ChatBean.TYPE_MINE_IMAGE;
            }
        }
    }

    /**
     * item＋item里的控件点击监听事件
     */
    private ChatAdapter.OnItemClickListener ChatItemClickListener = new ChatAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View v, int position) {
//            showToast("position: "+position+" | 内容: "+adapter.getDatas().get(position).message);
        }

        @Override
        public void onItemLongClick(View v, int position) {
            String content = contentEdit.getText().toString();
            content += (" @"+adapter.getDatas().get(position).username+" ");
            contentEdit.setText(content);
            contentEdit.setSelection(content.length());
        }
    };

    /** 获取聊天的历史记录 */
    private void getRecodeTask(){
        int recvId = commentID;
        if(isGroup){
            recvId = groupID;
        }

        String url = "";
        if(isGroup){
            url = "api/im/gmsg/";
        }else {
            url = "api/im/umsg/";
        }
        OkGo.<BaseBean<List<ChatRecodeBean>>>get(App.getHttpUrl(url)+recvId+"/"+Constants.PAGE_SIZE+"/"+pageNO)
                .tag(this)
                .execute(new DialogCallback<List<ChatRecodeBean>>(this, false) {
                    @Override
                    public void handleSuccess(List<ChatRecodeBean> data) {
                        if(data.size() < Constants.PAGE_SIZE){
                            isCanLoading = false;
                        }

                        buildDatas(data);
                    }
                });
    }

    private void initImagePicker(){
        imagePicker = new ImagePicker();
        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(true);
        imagePicker.setCallback(callback);
    }

    private void headPicker(boolean isCamera){
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(1)
                .capture(false)
                .isCamera(isCamera)
                .isSimpleChoose(true)
                .captureStrategy(new CaptureStrategy(true, "tq.com.tqstudent.fileProvider"))
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new MatisseImageEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    private List<Uri> mSelected;
    private List<String> images = new ArrayList<>();
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            images = Matisse.obtainPathResult(data);

            LogUtil.e("图片地址: "+images.get(0)+" | 图片的方向："+(ImgUtils.isImageLandscape(images.get(0)) ? "横屏" : "竖屏"));
//            testIV.setImageURI(Uri.fromFile(new File(images.get(0))));
            imagePicker.setCallback(callback);
            imagePicker.handlePickImage(this, images.get(0));
//            Log.d("Matisse", "mSelected: " + mSelected);
        } else {
            imagePicker.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void initCropImage(){
//        cImageView.setImageBitmap(getBitmap(R.drawable.right));//为了兼容小图片，必须在代码中加载图片
//        cImageView.rotateImage(30);//设定图片的旋转角度
//        cImageView.setFixedAspectRatio(true);//设置允许按比例截图，如果不设置就是默认的任意大小截图
//        cImageView.setAspectRatio(1, 1);//设置比例为一比一
//        cImageView.setGuidelines(CropImageView.ON);//设置显示网格的时机，默认为on_touch
    }

    private ImagePicker.Callback callback = new ImagePicker.Callback(){
        @Override
        public void onPickImage(Uri imageUri) {

        }

        public void onCropImage(Uri imageUri){
            testIV.setImageURI(imageUri);
            ChatBean bean = new ChatBean(ChatBean.TYPE_MINE_IMAGE, 1, UserInfo.getHeadImg(), UserInfo.getUserName(), "", "", imageUri);
            adapter.addData(bean);
            recyclerView.scrollToPosition(adapter.getItemCount()-1);
            uploadImageTask(FileUtil.getFilePathByUri(ChatActivity.this, imageUri));
        }

        @Override
        public void cropConfig(CropImage.ActivityBuilder builder) {
            VarietyUtil.initCropBuilder(builder);
        }

        @Override
        public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
            super.onPermissionDenied(requestCode, permissions, grantResults);
        }
    };

    private ITQIMObserver mITQIMObserver = new ITQIMObserver() {
        @Override
        public void onStatuesChange(TQIMStatus old, TQIMStatus n) {

        }

        @Override
        public void onRecvMsg(JSONObject pObject) {
            try {
                LogUtil.e("object: "+pObject.toString());
                ChatReceiveBean bean = new Gson().fromJson(pObject.toString(), ChatReceiveBean.class);

                int type = getBeanType(bean.suid, bean.ctype);
                ChatBean chat = null;
                if (type == ChatBean.TYPE_OPPOSITE_VIDEO) {
                    chat = initVideoType(bean);

                } else {
                    chat = new ChatBean(type, bean.ctype, bean.spic, bean.sname, bean.c, bean.c);
                }
                adapter.addData(chat);
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);

            } catch (Exception e){
                e.printStackTrace();
            }
        }

        public long to(){ //
            return commentID;
        }
        public long toGroup(){ //
            return groupID;
        }
        public long from(){
            return UserInfo.getUserID();
        }
    };

    // 只针对视频播放的
    private ChatBean initVideoType(ChatReceiveBean bean){
        ChatBean chat = new ChatBean();
        chat.title = "";
        chat.videoUrl = bean.c;
        chat.type = ChatBean.TYPE_OPPOSITE_VIDEO;
        chat.icon = bean.spic;
        chat.username = bean.sname;
        chat.matid = 0; // 私信不需要上传观看时长
        chat.attid = 0; //
        return chat;
    }

    //type 0 text, 1 image, 2 media, isSendText:发送的是否是文字
    private void sendMessage(String content, int type, boolean isSendText){
        TQIMMsg lMsg = new TQIMMsg();
        lMsg.setContent(content);
        lMsg.setContentType(type);
//        lMsg.setTo(UserInfo.getUserID());
        if(isGroup){
            lMsg.setToGroup(groupID);
            lMsg.setTo(0);
        } else {
            lMsg.setTo(commentID);
            lMsg.setToGroup(0);
        }

        lMsg.setMsgCallback(new TQIMMsg.TQIMMsgCallback() {
            @Override
            public void result(boolean isSuccess) {
                if(isSuccess){
                    if(isSendText) {
                        adapter.addData(new ChatBean(ChatBean.TYPE_MINE_TEXT, type, UserInfo.getHeadImg(), UserInfo.getUserName(), content, ""));
                        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
                        contentEdit.setText("");
                    }
                } else {
                    showToast("消息发送失败");
                }
            }
        });

        TQIM.getShareIm().sendMessage(lMsg);
    }

    /** 上传图片 */
    private void uploadImageTask(String path){
        OkGo.<SimpleBaseBean>post(App.getUploadUrl())
                .tag(this)
                .isMultipart(true)
                .params("file_type", "jpg")
                .params("file_tag", "head image")
                .params("file", new File(path))
                .execute(new SimpleDialogCallback(this) {
                    @Override
                    public void handleSuccess(SimpleBaseBean data) {
                        sendMessage(data.fid, ChatBean.TYPE_OPPOSITE_TEXT, false);
                    }
                });
    }

    /**
     * 设置小红点的已读
     * @param targetID
     * @param isGroup 目标类型： 0 表示是目标是普通用户， 1 表示目标是群组
     */
    private void setReadPoint(int targetID, boolean isGroup){
        String uri = "api/im/setread";
        String json = "{\"target_id\""+":"+targetID+",\"score\""+":"+(isGroup?1:0)+"}";
        OkGo.<String>post(App.getHttpUrl(uri))
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });

    }
}
